import java.util.Arrays;

public class TestHeap {
    public int[] elem;
    public int userSize; //记录当前堆当中有效的数据个数

    public TestHeap() {
        this.elem = new int[10];
    }

    //初始化elem
    public void initElem(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            userSize++;
        }
    }

    //创建堆
    public void createHeap() {
        for (int parent = (userSize - 1 - 1) / 2; parent >= 0; parent--) {
            siftDown(parent, userSize);
        }
    }

    public void siftDown(int parent, int len) {
        int child = 2 * parent + 1;
        while (child < len) {
            //左孩子和右孩子比较大小
            if (child + 1 < len && elem[child] < elem[child + 1]) {
                child = child + 1;
            }
            //走完上述语句，证明child下标一定保存的是左右孩子最大值的下标
            if (elem[child] > elem[parent]) {
                //交换
                swap(child,parent);
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }
        }
    }

    public void push(int val){
        if(isFull()){
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[userSize] = val;
        siftUp(userSize);
        userSize++;
    }
    public void swap(int i, int j){
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }
    public boolean isFull(){
        return userSize == elem.length;
    }
    public void siftUp(int child){
        int parent = (child-1)/2;
        while(child > 0) {
            if (elem[child] > elem[parent]) {
                swap(child, parent);
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }
    }

    public int pop(){
        //判空
        if(empty()){
            return -1;
        }
        int oldVal = elem[0];
        swap(0,userSize-1);
        userSize--;
        siftDown(0,userSize);
        return oldVal;
    }
    public boolean empty(){
        return userSize == 0;
    }

    public void heapSort(){
        int end = userSize-1;
        while(end >= 0){
            swap(0,end);
            siftDown(0,end);
            end--;
        }
    }
}
